//
//  testRunloop.swift
//  sinaDemo
//
//  Created by Xueming on 2021/4/12.
//

import Foundation
 
class Monitor {
  
  static let shared = Monitor()
  
  private var runLoopObserver: CFRunLoopObserver?
  private var dispatchSemaphore: DispatchSemaphore?
  private var runLoopActivity: CFRunLoopActivity?
  
  init() {}
  
  func beginMonitor() {
    guard self.runLoopObserver == nil else { return }
    
    self.dispatchSemaphore = DispatchSemaphore(value: 0)
 
    let info = Unmanaged<Monitor>.passUnretained(self).toOpaque()
    var context: CFRunLoopObserverContext = CFRunLoopObserverContext(version: 0, info: info, retain: nil, release: nil, copyDescription: nil)
    self.runLoopObserver = CFRunLoopObserverCreate(kCFAllocatorDefault, CFRunLoopActivity.allActivities.rawValue, true, 0, runLoopCallBack(), &context)
    
    CFRunLoopAddObserver(CFRunLoopGetCurrent(), self.runLoopObserver, CFRunLoopMode.commonModes)
    
    DispatchQueue.global().async {
      // 如果少于50每帧, 则认为卡顿
      while true {
        guard let sem = self.dispatchSemaphore?.wait(timeout: DispatchTime.now() + 1 / 50) else { return }
        if case DispatchTimeoutResult.timedOut = sem {
          guard let _ = self.runLoopObserver else {
            self.dispatchSemaphore = nil
            self.runLoopActivity = nil
            return
          }
          
          // beforeSources: 进入睡眠前
          // afterWaiting: 唤醒后的状态
          if (self.runLoopActivity == CFRunLoopActivity.beforeSources || self.runLoopActivity == CFRunLoopActivity.afterWaiting) {
            print("symbo: \(Thread.callStackSymbols)")
            print("打印卡顿堆栈...")
          }
        }
      }
    }
  }
  
  func endMonitor() {
    if self.runLoopObserver != nil {
      return
    }
    
    CFRunLoopRemoveObserver(CFRunLoopGetCurrent(), self.runLoopObserver, CFRunLoopMode.commonModes)
    self.runLoopObserver = nil
  }
  
}
 
extension Monitor {
  func runLoopCallBack() -> CFRunLoopObserverCallBack {
    return { (observer, activity, context) -> Void in
      let weakSelf = Unmanaged<Monitor>.fromOpaque(context!).takeUnretainedValue()
      weakSelf.runLoopActivity = activity
      weakSelf.dispatchSemaphore?.signal()
    }
  }
}
